package com.zhy.baselibrary.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<V : ViewBinding, out VM : BaseViewModel> : Fragment() {

    private var parentView: View? = null

    protected lateinit var binding: V


    val model by lazy {
        val type = javaClass.genericSuperclass as ParameterizedType
        val clazz = type.actualTypeArguments[1] as Class<VM>
        ViewModelProvider(this).get(clazz) as VM
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initialize()
        setListener()
        setData()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        binding = method.invoke(null, layoutInflater, container, false) as V
        if (parentView == null) parentView = binding.root
        return parentView
    }


    open fun setListener() {

    }

    abstract fun initialize()

    open fun setData() {}

    open fun <T : BaseViewModel> getFraViewModel(cls: Class<T>?): T {
        val vm = ViewModelProvider(this)[cls!!]
        return vm
    }


    open fun getViewModel(): BaseViewModel? {
        return null
    }
    open fun <T : BaseViewModel> getViewModel(cls: Class<T>?): T {
        val vm = ViewModelProvider(this)[cls!!]
        return vm
    }


    protected fun launchActivity(clazz: Class<*>) {
        startActivity(Intent(context, clazz))
    }

    protected fun launchActivity(clazz: Class<*>, bundle: Bundle) {
        val intent = Intent(context, clazz)
        intent.putExtras(bundle)
        startActivity(intent)
    }
}